import multiprocessing
import os
import re
import time
import datetime
import numpy as np
from flask import Flask, current_app, request
from flask import render_template
from flask_socketio import SocketIO, emit
from neuracle_lib.triggerBox import TriggerBox
from utils import bci_utils

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

app.time = None
app.number = 0

app.triggerbox = None

@app.route("/start_experiment", methods=['GET','POST'])
def start_experiment():
    try:
        app.triggerbox = TriggerBox("COM4")
    except Exception as e:
        print("---异常---：", e)
        print("启动失败")
        return 'error'

    print('启动成功')
    return 'success'



@app.route("/", methods=['GET','POST'])
def index():
    """
    index主页面
    """

    return render_template('index.html')

@app.route("/rest", methods=['GET','POST'])
def up_rest():

    return render_template('rest.html')


@socketio.event
def play_cue_tone(message):
    print(message['signal'])
    if message['signal']=='open_eyes':
        bci_utils.cue_tone_open_eyes()
    elif message['signal'] == 'close_eyes':
        bci_utils.cue_tone_close_eyes()
    elif message['signal'] == 'end':
        bci_utils.cue_tone_end()



@socketio.event
def data_acq(message):


    print('send label: {0}'.format(message['label']))
    if app.triggerbox is not None:
        app.triggerbox.output_event_data(message['label'])







if __name__ == "__main__":
    # start_experiment()
    socketio.run(app, allow_unsafe_werkzeug=True, host='0.0.0.0', port=5000)
